
import {  Button, Radio, Toast } from "antd-mobile";
import { useLocation, useNavigate } from "react-router-dom";
import { useEffect, useState } from 'react';
// import AlipayService from '../../api/alipay';

function Index() {

  const nav = useNavigate();
  const location = useLocation();

  const [selectedPayment, setSelectedPayment] = useState<string>('');
  const [paymentInfo, setPaymentInfo] = useState<any>(null);
  const [orderInfo, setOrderInfo] = useState<any>(null);
  const [isPaying, setIsPaying] = useState<boolean>(false);

  type PaymentInfo = {
    patientName: string;
    registrationNumber: string;
    department: string;
    doctorName: string;
    prescriptionTime: string;
  }

  type OrderInfo = {
    orderNumber: string;
    orderTime: string;
    paymentAmount: number;
  }

  const handleBack = () => {
    nav(-1);
  };

  const handlePaymentChange = (value: string) => {
    setSelectedPayment(value);
  };

  const handleConfirmPayment = async () => {
    if (!selectedPayment) {
      Toast.show('请选择支付方式');
      return;
    }
    
    // 读取订单（来自 state 或 localStorage）
    let pending: any = (location.state as any)?.order;
    if (!pending) {
      try {
        const raw = localStorage.getItem('danPendingOrder');
        if (raw) pending = JSON.parse(raw);
        nav('/order-detail')
      } catch {
        console.log('读取订单数据失败');   
            
      }
    
    }

    if (!pending) {
      Toast.show('订单信息不存在，请重新下单');
      return;
    }

    // 兼容不同页面的价格字段
    const paymentAmount = pending.totalAmount || pending.amount || 0;
    console.log('确认缴费 - 订单金额:', paymentAmount);

    // 所有支付方式都跳转到订单详情页面
    setIsPaying(true);
    
    try {
      // 模拟支付处理时间
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 跳转到订单详情页面，确保传递正确的价格数据
      nav('/order-detail', { 
        state: { 
          order: {
            ...pending,
            totalAmount: paymentAmount, // 统一使用totalAmount字段
            amount: paymentAmount       // 同时保留amount字段以兼容
          }, 
          paymentMethod: selectedPayment,
          paymentStatus: 'pending' // 支付状态：待支付
        } 
      });
    } catch (error) {
      console.error('跳转失败:', error);
      Toast.show('跳转失败，请重试');
      setIsPaying(false);
    }
  };

  useEffect(() => {
    // 优先读取从上一个页面带入的订单
    const stateOrder = (location.state as any)?.order;
    console.log('zhi页面 - 从location.state获取的订单数据:', stateOrder);
    
    // 如果从上个页面携带了支付方式，则默认选中
    const fromPayment = (location.state as any)?.payment;
    if (fromPayment) {
      setSelectedPayment(fromPayment);
      console.log('zhi页面 - 默认选中支付方式:', fromPayment);
    }
    
    let pending = stateOrder;
    if (!pending) {
      try {
        const raw = localStorage.getItem('danPendingOrder');
        if (raw) {
          pending = JSON.parse(raw);          
          console.log('zhi页面 - 从localStorage获取的订单数据:', pending);
        }
      } catch {
        console.log('读取订单数据失败');
      }
    }

    // 监听支付宝支付回调
    const handleAlipayCallback = (event: MessageEvent) => {
      if (event.data && event.data.type === 'alipay_callback') {
        const { success } = event.data;
        if (success) {
          Toast.show('支付成功！');
          // 跳转到订单详情页
          nav('/order-detail', { state: { order: pending, paymentMethod: 'alipay' } });
        } else {
          Toast.show('支付失败，请重试');
        }
      }
    };

    // 添加消息监听器（清理放到 useEffect 末尾统一返回）
    window.addEventListener('message', handleAlipayCallback);

    if (pending) {
      console.log('从上个页面获取的订单数据:', pending);
      
      // 兼容不同页面的价格字段：dan页面用totalAmount，que页面用amount
      const paymentAmount = pending.totalAmount || pending.amount || 0;
      console.log('订单总金额:', paymentAmount);
      
      const mockPaymentInfo: PaymentInfo = {
        patientName: '王小柯',
        registrationNumber: '20200101001598Z',
        department: '门诊外一科',
        doctorName: '刘医师',
        prescriptionTime: new Date(pending.createdAt || Date.now()).toLocaleString(),
      };
      const mockOrderInfo: OrderInfo = {
        orderNumber: pending.orderNo || 'D0000000000',
        orderTime: new Date(pending.createdAt || Date.now()).toLocaleString(),
        paymentAmount: paymentAmount,
      };
      
      console.log('设置的订单信息:', mockOrderInfo);
      setPaymentInfo(mockPaymentInfo);
      setOrderInfo(mockOrderInfo);
    } else {
      // 兜底：保留原有示例数据
      const mockPaymentInfo: PaymentInfo = {
        patientName: '王小柯',
        registrationNumber: '20200101001598Z',
        department: '门诊外一科',
        doctorName: '刘医师',
        prescriptionTime: '2020-01-01 10:20:36',
      };
      const mockOrderInfo: OrderInfo = {
        orderNumber: '2021010156256894',
        orderTime: '2020-01-01 10:23:36',
        paymentAmount: 520.13,
      };
      setPaymentInfo(mockPaymentInfo);
      setOrderInfo(mockOrderInfo);
    }

    // 清理函数
    return () => {
      window.removeEventListener('message', handleAlipayCallback);
    };
  }, [location.state]);

  return (
    <div style={{ width: '100vw', minHeight: '100vh', background: '#f5f5f5' }}>
      {/* 顶部导航栏 */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        padding: '12px 16px',
        background: '#fff',
        borderBottom: '1px solid #f0f0f0'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div 
            onClick={handleBack}
            style={{ 
              fontSize: '20px', 
              cursor: 'pointer',
              color: '#333'
            }}
          >
            ‹
          </div>
          <div style={{ fontSize: '18px', fontWeight: 600, color: '#333' }}>
            确认缴费
          </div>
        </div>
       
      </div>

      {/* 缴费信息卡片 */}
      {paymentInfo && (
        <div style={{
          margin: '16px',
          background: '#fff',
          borderRadius: '12px',
          padding: '16px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <div style={{ 
            fontSize: '16px', 
            fontWeight: 600, 
            color: '#333',
            marginBottom: '16px'
          }}>
            缴费信息
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>就诊人</span>
            <span style={{ fontSize: '14px', color: '#333', fontWeight: 500 }}>
              {paymentInfo.patientName}
            </span>
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>登记号</span>
            <span style={{ fontSize: '14px', color: '#333', fontWeight: 500 }}>
              {paymentInfo.registrationNumber}
            </span>
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>就诊科室</span>
            <span style={{ fontSize: '14px', color: '#333', fontWeight: 500 }}>
              {paymentInfo.department}
            </span>
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>开单医生</span>
            <span style={{ fontSize: '14px', color: '#333', fontWeight: 500 }}>
              {paymentInfo.doctorName}
            </span>
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>开单时间</span>
            <span style={{ fontSize: '14px', color: '#333', fontWeight: 500 }}>
              {paymentInfo.prescriptionTime}
            </span>
          </div>
        </div>
      )}

      {/* 订单信息卡片 */}
      {orderInfo && (
        <div style={{
          margin: '0 16px 16px',
          background: '#fff',
          borderRadius: '12px',
          padding: '16px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <div style={{ 
            fontSize: '16px', 
            fontWeight: 600, 
            color: '#333',
            marginBottom: '16px'
          }}>
            订单信息
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>订单编号</span>
            <span style={{ fontSize: '14px', color: '#333', fontWeight: 500 }}>
              {orderInfo.orderNumber}
            </span>
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>下单时间</span>
            <span style={{ fontSize: '14px', color: '#333', fontWeight: 500 }}>
              {orderInfo.orderTime}
            </span>
          </div>
          
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <span style={{ fontSize: '14px', color: '#999' }}>支付金额</span>
            <span style={{ fontSize: '16px', color: '#ff4d4f', fontWeight: 600 }}>
              ¥{orderInfo.paymentAmount.toFixed(2)}
            </span>
          </div>
        </div>
      )}

      {/* 支付方式卡片 */}
      <div style={{
        margin: '0 16px 16px',
        background: '#fff',
        borderRadius: '12px',
        padding: '16px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <div style={{ 
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: '16px'
        }}>
          <div style={{ 
            fontSize: '16px', 
            fontWeight: 600, 
            color: '#333'
          }}>
            支付方式
          </div>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '8px'
          }}>
            <span style={{ fontSize: '14px', color: '#999' }}>应付金额</span>
            <span style={{ 
              fontSize: '20px', 
              color: '#ff4d4f', 
              fontWeight: 700 
            }}>
              ¥{orderInfo?.paymentAmount?.toFixed(2) || '0.00'}
            </span>
          </div>
        </div>
        
        <Radio.Group value={selectedPayment} onChange={handlePaymentChange}>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '16px 12px',
            marginBottom: '8px',
            borderBottom: '1px solid #f0f0f0',
            borderRadius: '8px',
            backgroundColor: selectedPayment === 'self-pay' ? '#f6ffed' : 'transparent',
            border: selectedPayment === 'self-pay' ? '1px solid #b7eb8f' : '1px solid transparent',
            transition: 'all 0.3s ease'
          }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
              <span style={{ fontSize: '16px', color: '#333', fontWeight: 500 }}>自费支付</span>
              <span style={{ fontSize: '12px', color: '#999' }}>支付宝/微信支付</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                alignItems: 'flex-end',
                gap: '2px'
              }}>
                <span style={{ fontSize: '18px', color: '#ff4d4f', fontWeight: 600 }}>
                  ¥{orderInfo?.paymentAmount?.toFixed(2) || '0.00'}
                </span>
                <span style={{ fontSize: '10px', color: '#999' }}>全额支付</span>
              </div>
              <Radio value="self-pay" />
            </div>
          </div>
          <div style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '16px 12px',
            borderRadius: '8px',
            backgroundColor: selectedPayment === 'insurance' ? '#f6ffed' : 'transparent',
            border: selectedPayment === 'insurance' ? '1px solid #b7eb8f' : '1px solid transparent',
            transition: 'all 0.3s ease'
          }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
              <span style={{ fontSize: '16px', color: '#333', fontWeight: 500 }}>医保支付</span>
              <span style={{ fontSize: '12px', color: '#999' }}>医保卡直接扣费</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div style={{ 
                display: 'flex', 
                flexDirection: 'column', 
                alignItems: 'flex-end',
                gap: '2px'
              }}>
                <span style={{ fontSize: '18px', color: '#ff4d4f', fontWeight: 600 }}>
                  ¥{orderInfo?.paymentAmount?.toFixed(2) || '0.00'}
                  
                </span>
                <span style={{ fontSize: '10px', color: '#52c41a' }}>医保报销</span>
              </div>
              <Radio value="insurance" />
            </div>
          </div>
        </Radio.Group>
      </div>

      {/* 当选择自费支付时显示：支付宝支付卡片 */}
      {selectedPayment === 'self-pay' && (
        <div style={{
          margin: '0 16px 16px',
          background: '#fff',
          borderRadius: '12px',
          padding: '16px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <div style={{
                width: 36,
                height: 36,
                borderRadius: 8,
                background: '#00A3EE',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#fff',
                fontWeight: 700
              }}>支</div>
              <div style={{ fontSize: 16, color: '#333', fontWeight: 600 }}>支付宝支付</div>
            </div>
            <Button 
              color="primary" 
              size="small" 
              onClick={handleConfirmPayment}
              loading={isPaying}
              disabled={isPaying}
            >
              {isPaying ? '支付中...' : '立即支付'}
            </Button>
          </div>
          <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
            {isPaying ? '正在处理，请稍候...' : '将跳转到订单详情页面'}
          </div>
        </div>
      )}

      {/* 底部确认缴费按钮 */}
      <div style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        padding: '16px',
        background: '#fff',
        borderTop: '1px solid #f0f0f0'
      }}>
        <Button
          color="primary"
          block
          size="large"
          onClick={handleConfirmPayment}
          loading={isPaying}
          disabled={isPaying}
          style={{
            borderRadius: '8px',
            height: '48px',
            fontSize: '16px',
            fontWeight: 600
          }}
        >
          {isPaying ? '处理中...' : '确认缴费'}
        </Button>
      </div>

      {/* 底部占位，避免按钮遮挡内容 */}
      <div style={{ height: '80px' }}>
      
      </div>
    </div>
  );
}

export default Index;
